#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include <jsoncpp/json/json.h>
#include <functional>

using namespace SocketModule;

// client -> server

class Request
{
public:
    Request() {}
    Request(int x, int y, int oper)
        : _x(x),
          _y(y),
          _oper(oper)
    {
    }
    // 序列化
    std::string Serialize()
    {
        // _x = 10 _y = 20, _oper = '+'
        // "10" "20" '+' : 用空格作为分隔符

        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::FastWriter write;
        std::string s = write.write(root);
        return s;
    }
    bool Deserialize(std::string &in)
    {
        // "10" "20" '+' -> 以空格作为分隔符 -> 10 20 '+'
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
        }
        return ok;
    }

    int X()
    {
        return _x;
    }
    int Y()
    {
        return _y;
    }
    int Oper()
    {
        return _oper;
    }

    ~Request() {}

private:
    int _x;
    int _y;
    int _oper; // 运算符
};
// server -> client
class Response
{
public:
    Response() {}
    Response(int result, int code) : _result(result), _code(code)
    {
    }
    std::string Serialize()
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;
        Json::FastWriter writer;
        return writer.write(root);
    }
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
        }
        return ok;
    }

    void SetResult(int result)
    {
        _result = result;
    }
    void SetCode(int code)
    {
        _code = code;
    }
    void ShowResult()
    {
        std::cout << "计算结果是: " << _result << "[" << _code << "]" << std::endl;
    }

    ~Response() {}

private:
    int _result; // 运算结果，无法区分清楚应答是计算结果，还是异常值
    int _code;   // 0:sucess, 1,2,3,4->不同的运算异常的情况:如除零等情况
};

// 协议(基于TCP的)
// 读取的时候，读到完整的请求(TCP, UDP不用考虑)

using func_t = std::function<Response(Request &req)>;

const std::string sep = "\r\n"; // 报文分割符

class Protocol
{
public:
    Protocol()
    {
    }
    Protocol(func_t func) : _func(func)
    {
    }

    std::string Encode(const std::string &jsonstr)
    {
        // 50\r\n{"x": 10, "y" : 20, "oper" : '+'}\r\n
        std::string len = std::to_string(jsonstr.size());
        return len + sep + jsonstr + sep;
    }
    // 50\r\n{"x": 10, "y" : 20, "oper" : '+'}\r\n
    bool Decode(std::string &buffer, std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if (pos = std::string::npos)
        {
            return false; // 让调用方继续从内核中读取数据
        }
        std::string package_len_str = buffer.substr(0, pos);
        int package_len_int = std::stoi(package_len_str);
        int target_len = package_len_str.size() + 2 * sep.size() + package_len_int;
        if (buffer.size() != target_len)
            return false;
        *package = buffer.substr(pos + sep.size(), package_len_int);
        buffer.erase(0, target_len);
        return true;
    }

    void GetRequest(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string buffer_queue;
        while (true)
        {
            int n = sock->Recv(&buffer_queue);
            if (n > 0)
            {
                std::cout << "-----------request_buffer--------------" << std::endl;
                std::cout << buffer_queue << std::endl;
                std::cout << "------------------------------------" << std::endl;
                std::string json_package;
                // 1. 解析报文，提取完整的json请求，如果不完整，就让服务器继续读取
                // bool ret = Decode(buffer_queue, &json_package);
                // if (!ret)
                // {
                //     continue;
                // }
                while (Decode(buffer_queue, &json_package))
                {
                    // 2.请求json串，反序列化
                    Request req;
                    bool ok = req.Deserialize(json_package);
                    if (!ok)
                        continue;
                    // 3.计算
                    Response resp = _func(req);
                    // 4.序列化
                    std::string json_str = resp.Serialize();
                    // 5. 添加自定义长度,取有效长度
                    std::string send_str = Encode(json_str); // 携带长度的应答报文了"len\r\n{result:XXX, code:XX}\r\n"
                    // 6.发送
                    sock->Send(send_str);
                }
            }
            if (n == 0)
            {
                LOG(LogLevel::INFO) << "client:" << client.StringAddr() << "Quit!";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "client:" << client.StringAddr() << ", recv error";
                break;
            }
        }
    }
    bool GetResponse(std::shared_ptr<Socket> &client, std::string &resp_buff, Response *resp)
    {
        while (true)
        {
            int n = client->Recv(&resp_buff);
            if (n > 0)
            {
                std::cout << "-----------resp_buffer--------------" << std::endl;
                std::cout << resp_buff << std::endl;
                std::cout << "------------------------------------" << std::endl;

                std::string json_package;

                // 1. 解析报文，提取完整的json请求，如果不完整，就让服务器继续读取
                //  bool ret = Decode(resp_buff, &json_package);
                //  if (!ret)
                //      continue;

                while (Decode(resp_buff, &json_package))
                {
                    // 2. 反序列化
                    resp->Deserialize(json_package);
                }
                return true;
            }
            else if (n == 0)
            {
                std::cout << "server quit " << std::endl;
                return false;
            }
            else
            {
                std::cout << "recv error" << std::endl;
                return false;
            }
        }
    }
    std::string BuildRequestString(int x, int y, char oper)
    {
        // 1. 构建一个完整的请求
        Request req(x, y, oper);
        // 2. 序列化
        std::string json_req = req.Serialize();

        // 2.1 debug
        std::cout << "------------json_req string------------" << std::endl;
        std::cout << json_req << std::endl;
        std::cout << "---------------------------------------" << std::endl;

        // 3. 添加长度报头
        return Encode(json_req);
    }
    ~Protocol()
    {
    }

private:
    func_t _func;
};